<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable @change="handleQuery">
          <el-option v-for="p in projectOptions" :key="p.projectId" :label="p.projectName" :value="p.projectId" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择开始日期"
          value-format="YYYY-MM-DD"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="YYYY-MM-DD"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <!-- 项目统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon project">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">项目总数</div>
              <div class="stats-value">{{ projectStats.totalProjects || 0 }}</div>
              <div class="stats-detail">
                进行中: {{ projectStats.activeProjects || 0 }} | 
                已完成: {{ projectStats.completedProjects || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 任务统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon task">
              <el-icon><List /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">任务总数</div>
              <div class="stats-value">{{ taskStats.totalTasks || 0 }}</div>
              <div class="stats-detail">
                完成率: {{ taskStats.taskCompletionRate || 0 }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 时间统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon time">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">总工时</div>
              <div class="stats-value">{{ timeStats.totalHours || 0 }}h</div>
              <div class="stats-detail">
                可计费: {{ timeStats.billableHours || 0 }}h
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 成员统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon member">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">成员总数</div>
              <div class="stats-value">{{ memberStats.totalMembers || 0 }}</div>
              <div class="stats-detail">
                活跃: {{ memberStats.activeMembers || 0 }} | 
                本月新增: {{ memberStats.newMembersThisMonth || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 项目进度统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>项目进度统计</span>
            </div>
          </template>
          <div ref="projectProgressChart" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 任务状态分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>任务状态分布</span>
            </div>
          </template>
          <div ref="taskStatusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 时间跟踪统计表格 -->
    <el-card class="table-section">
      <template #header>
        <div class="card-header">
          <span>时间跟踪统计</span>
        </div>
      </template>
      <el-table :data="timeTrackingStats" v-loading="loading" stripe>
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="projectName" label="项目" show-overflow-tooltip />
        <el-table-column prop="taskName" label="任务" show-overflow-tooltip />
        <el-table-column prop="userName" label="成员" width="120" />
        <el-table-column prop="hours" label="工时" width="100" align="right">
          <template #default="scope">
            {{ scope.row.hours }}h
          </template>
        </el-table-column>
        <el-table-column prop="recordCount" label="记录数" width="100" align="center" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Search, Refresh, Folder, List, Clock, User } from '@element-plus/icons-vue'
import { listProject } from '@/api/pm/project'
import { 
  getProjectStats, 
  getTaskStats, 
  getTimeStats, 
  getMemberStats,
  getProjectProgressStats,
  getTaskStatusStats,
  getTimeTrackingStats,
  type ProjectStats,
  type TaskStats,
  type TimeStats,
  type MemberStats,
  type ProjectProgressStats,
  type TaskStatusStats,
  type TimeTrackingStats
} from '@/api/pm/report'
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance() as any

// 响应式数据
const loading = ref(false)
const showSearch = ref(true)
const projectOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive({
  projectId: undefined,
  startDate: undefined,
  endDate: undefined
})

// 统计数据
const projectStats = ref<ProjectStats>({
  totalProjects: 0,
  activeProjects: 0,
  completedProjects: 0,
  overdueProjects: 0,
  completionRate: 0
})

const taskStats = ref<TaskStats>({
  totalTasks: 0,
  completedTasks: 0,
  inProgressTasks: 0,
  pendingTasks: 0,
  overdueTasks: 0,
  taskCompletionRate: 0
})

const timeStats = ref<TimeStats>({
  totalHours: 0,
  billableHours: 0,
  nonBillableHours: 0,
  averageHoursPerDay: 0,
  totalRecords: 0
})

const memberStats = ref<MemberStats>({
  totalMembers: 0,
  activeMembers: 0,
  inactiveMembers: 0,
  newMembersThisMonth: 0
})

const projectProgressStats = ref<ProjectProgressStats[]>([])
const taskStatusStats = ref<TaskStatusStats[]>([])
const timeTrackingStats = ref<TimeTrackingStats[]>([])

// 图表引用
const projectProgressChart = ref<HTMLElement>()
const taskStatusChart = ref<HTMLElement>()

// 加载项目列表
const loadProjects = () => {
  listProject({ pageNum: 1, pageSize: 1000 }).then(res => {
    projectOptions.value = res.rows || []
  }).catch(err => {
    console.error('加载项目列表失败', err)
    projectOptions.value = []
  })
}

// 加载统计数据
const loadStats = () => {
  loading.value = true
  
  Promise.all([
    getProjectStats(),
    getTaskStats(queryParams),
    getTimeStats(queryParams),
    getMemberStats(queryParams),
    getProjectProgressStats(),
    getTaskStatusStats(queryParams),
    getTimeTrackingStats(queryParams)
  ]).then(([projectRes, taskRes, timeRes, memberRes, progressRes, statusRes, trackingRes]) => {
    projectStats.value = projectRes.data || {}
    taskStats.value = taskRes.data || {}
    timeStats.value = timeRes.data || {}
    memberStats.value = memberRes.data || {}
    projectProgressStats.value = progressRes.data || []
    taskStatusStats.value = statusRes.data || []
    timeTrackingStats.value = trackingRes.data || []
    
    // 渲染图表
    nextTick(() => {
      renderProjectProgressChart()
      renderTaskStatusChart()
    })
  }).catch(err => {
    console.error('加载统计数据失败', err)
    proxy?.$modal.msgError('加载统计数据失败')
  }).finally(() => {
    loading.value = false
  })
}

// 渲染项目进度图表
const renderProjectProgressChart = () => {
  if (!projectProgressChart.value) return
  
  const chart = echarts.init(projectProgressChart.value)
  const data = projectProgressStats.value.map(item => ({
    name: item.projectName,
    value: item.progress
  }))
  
  const option = {
    title: {
      text: '项目完成进度',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    series: [{
      name: '完成进度',
      type: 'bar',
      data: data,
      itemStyle: {
        color: function(params: any) {
          const colors = ['#67C23A', '#E6A23C', '#F56C6C', '#909399']
          return colors[params.dataIndex % colors.length]
        }
      }
    }],
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      max: 100
    }
  }
  
  chart.setOption(option)
}

// 渲染任务状态分布图表
const renderTaskStatusChart = () => {
  if (!taskStatusChart.value) return
  
  const chart = echarts.init(taskStatusChart.value)
  const data = taskStatusStats.value.map(item => ({
    name: item.statusName,
    value: item.count
  }))
  
  const option = {
    title: {
      text: '任务状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '任务状态',
      type: 'pie',
      radius: '60%',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  chart.setOption(option)
}

// 查询
const handleQuery = () => {
  loadStats()
}

// 重置查询
const resetQuery = () => {
  queryParams.projectId = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  handleQuery()
}

// 页面加载
onMounted(() => {
  loadProjects()
  loadStats()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
  
  .stats-card {
    height: 120px;
    
    .stats-content {
      display: flex;
      align-items: center;
      height: 100%;
      
      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        font-size: 24px;
        color: white;
        
        &.project {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.task {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.time {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.member {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
      
      .stats-info {
        flex: 1;
        
        .stats-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 8px;
        }
        
        .stats-value {
          font-size: 28px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 8px;
        }
        
        .stats-detail {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.chart-section {
  margin-bottom: 20px;
}

.table-section {
  .card-header {
    font-weight: bold;
    color: #303133;
  }
}

:deep(.el-card__header) {
  padding: 18px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>